import 'package:flutter/foundation.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../model/book.dart';
import '../service/book_api_service.dart';

class BookProvider with ChangeNotifier {
  final BookApiService _apiService;
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;
  List<Book> _books = [];
  bool _isLoading = false;
  String? _error;

  List<Book> get books => _books;
  bool get isLoading => _isLoading;
  String? get error => _error;

  BookProvider({required BookApiService apiService}) : _apiService = apiService;

  Future<void> fetchBooks1() async {
    try {
      final querySnapshot = await _firestore.collection('books').get();
      _books = querySnapshot.docs
          .map((doc) => Book.fromJson({'id': doc.id, ...doc.data()}))
          .toList();
      notifyListeners();
    } catch (error) {
      throw error;
    }
  }

  Future<void> addBook1(Book book) async {
    try {
      final docRef = await _firestore.collection('books').add(book.toJson());
      _books.add(Book.fromJson({'id': docRef.id, ...book.toJson()}));
      notifyListeners();
    } catch (error) {
      throw error;
    }
  }

  Future<Book?> getBookByIsbn1(String isbn) async {
    try {
      final querySnapshot = await _firestore
          .collection('books')
          .where('isbn', isEqualTo: isbn)
          .limit(1)
          .get();
      if (querySnapshot.docs.isNotEmpty) {
        return Book.fromJson({
          'id': querySnapshot.docs.first.id,
          ...querySnapshot.docs.first.data()
        });
      }
      return null;
    } catch (error) {
      throw error;
    }
  }


  Future<void> fetchBooks() async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      // 先尝试从缓存加载
      final cachedBooks = await _apiService.getCachedBooks();
      if (cachedBooks.isNotEmpty) {
        _books = cachedBooks;
        notifyListeners();
      }

      // 再从网络加载
      final freshBooks = await _apiService.fetchBooks();
      _books = freshBooks;
      await _apiService.cacheBooks(_books);
    } catch (e) {
      _error = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Future<Book?> getBookByIsbn(String isbn) async {
    try {
      return await _apiService.getBookByIsbn(isbn);
    } catch (e) {
      _error = e.toString();
      notifyListeners();
      return null;
    }
  }

  Future<void> addBook(Book book) async {
    _isLoading = true;
    notifyListeners();

    try {
      final newBook = await _apiService.addBook(book);
      _books.add(newBook);
      await _apiService.cacheBooks(_books);
    } catch (e) {
      _error = e.toString();
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }


}